package hsb.ruoyi.common.mybatisplus;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @author 胡帅博
 * @date 2022/9/23 17:25
 * <p>
 * 根据某个字段批量查询
 */
public class selectBatchByField extends AbstractMethod {

    static String sql = "<script>SELECT %s FROM %s WHERE %s IN (%s)</script>";
    static String name = "selectBatchByField";

    public selectBatchByField() {
        super(name);
    }

    /**
     * @param name 方法名
     * @since 3.5.0
     */
    public selectBatchByField(String name) {
        super(name);
    }

    /**
     * 这个方法是想用来可以自定义批量查询使用的字段， 根据任意字段批量查询，
     * 但是需要字段名硬编码，也有解决的办法，就是传递 SFunction<T, ?> func  传递字段的get方法，然后自定义mybatis 的typeHandle来做转换
     * <p>
     * 类似:
     * LambdaMeta meta = LambdaUtils.extract(AppPlantMaterialRecord::getPlantOpRecordId);
     * String fieldName = PropertyNamer.methodToProperty(meta.getImplMethodName());
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(sql,
                sqlSelectColumns(tableInfo, false)
                , tableInfo.getTableName()
                , "${param1}"
                , SqlScriptUtils.convertForeach("#{item}", COLL, null, "item", COMMA)
        ), Object.class);
        return addSelectMappedStatementForTable(mapperClass, name, sqlSource, tableInfo);
    }
}

